package com.lfd.scheduled;

import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.config.ScheduledTask;

import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;


@SpringBootApplication
@Slf4j
public class ScheduledApplication implements ApplicationRunner {

    public static void main(String[] args) {
        SpringApplication.run(ScheduledApplication.class, args);
    }

    /**
     * 1. 使用 ScheduledExecutorService
     */
    void testScheduledTask() {
        ScheduledExecutorService scheduled = Executors.newScheduledThreadPool(1);
        Runnable runnable = new Runnable() {
            @Override
            public void run() {
                log.info("scheduled执行定时任务:{}", System.currentTimeMillis());
            }
        };
        scheduled.scheduleAtFixedRate(runnable, 1, 3, TimeUnit.SECONDS);
    }

    /**
     * 2. 使用 Timer 类
     * Timer 类和 TimerTask 是比较老的方法，但也可以用来创建简单的定时任务。
     */
    public void testTimer(){
        Timer timer = new Timer();
        TimerTask timerTask = new TimerTask() {
            @Override
            public void run() {
                log.info("Timer执行定时任务:{}", System.currentTimeMillis());
            }
        };
        // 延迟2秒后执行任务，每隔5秒执行一次
        timer.scheduleAtFixedRate(timerTask,2000,5000);

    }

    /***
     * 3. 使用 Spring 的 @Scheduled 注解
     */

    @Override
    public void run(ApplicationArguments args) throws Exception {
//        testScheduledTask();
//        testTimer();
    }
}
